<?php
  
  // This is for drop-down menus in the search box
  $db = new mysqli('localhost', 'mykaryoview' ,'genomes', 'mykaryoview');
        if(!$db) {
    // Show error if we cannot connect.
    echo 'ERROR: Could not connect to the database.';
  } else {
    // Is there a posted query string?
    if(isset($_POST['query'])) {
      $queryString = $db->real_escape_string($_POST['query']);
      
      // Is the string length greater than 0?
      
      if(strlen($queryString) >0) {
        /* SEARCH BY SNP */
        if (preg_match("/^rs\d+/", $queryString)) {   
            $query= $db->query("SELECT id as name,chr,position as chr_start,position as chr_end FROM snp WHERE id LIKE '$queryString%' LIMIT 10");         
            while ($result = $query ->fetch_object()) {
                $start  = $result->chr_start - 10000;
                if($start < 0){ $start = 0;}
                $end    = $result->chr_end   + 10000;
                $coords = $result->chr.':'.$start.','.$end;   
                echo $coords;        
                   // echo '{ "coords": "'+$coords+'"}';
                  }   
          /* SEARCH BY GENE NAME */
        } elseif ($queryString) { 
            $query= $db->query("SELECT name,chr,chr_start,chr_end FROM hgnc_genes WHERE name LIKE '$queryString%' LIMIT 10");         
            while ($result = $query ->fetch_object()) {
                $coords = $result->chr.':'.$result->chr_start.','.$result->chr_end;           
                   // echo '{ "coords": "'+$coords+'"}';
                   echo $coords;
                  }         
        } else {
          echo 'ERROR: There was a problem with the query.';
        }
      } else {
        // Dont do anything.
      } // There is a queryString.
    } else {
      echo 'There should be no direct access to this script!';
    }
  }
?>
